<?php

namespace App\Http\Controllers\Admin\Attachment;

use Illuminate\Http\Request;
use App\Http\Controllers\Admin\Controller;

class UploadController extends Controller{

	/* 上传文件后缀 */
	protected $ext = [];
	/* 上传大小限制 */
	protected $fileSizeLimit = 0;
	public function __construct(){
		$this->ext = [
			'png',
			'jpg',
			'jpeg',
			'gif',
			'bmp'
		];

		$this->fileSizeLimit = 200*1024;
	}

	public function save(Request $request){
		if(!$request->hasFile('file')){
			return $this->error('上传文件不存在！');
		}

		$file = $request->file('file');

		if(!$file->isValid()){
			return $this->error('上传文件失败！');
		}

		$ext = $file->guessExtension();
		if($ext == 'jpeg') $ext = 'jpg';
		$org_ext = $file->getClientOriginalExtension();

		if($ext != $org_ext){
			return $this->error('文件后缀不匹配！');
		}

		if(!in_array($ext, $this->ext)){
			return $this->error('只能上传'.implode(',', $this->ext).'格式的文件！');
		}

		if($file->getClientSize() > $this->fileSizeLimit){
			return $this->error('文件大小不能超过'. ($this->fileSizeLimit / 1024) . 'KB');
		}

		$filename =  date('Y-m-d') . '-' . uniqid() . '.' . $org_ext;
		$path = $file->storeAs('admin/upload/headimg',$filename);
		
		if($path){
			return $this->success('上传成功！',1,null,['path'=> '/' . $path]);
		}
	}
}